package com.forlove.app.qselect.friend.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.Html;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.widget.dialog.AnimationType;
import com.forlove.app.manager.QRCodeManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.login.entity.UserEntity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by yjl on 2017/10/23.
 */

public class ShowQRCodeDialog extends Dialog {
    private Window mWindow;
    private Context mContext;

    /**
     * 进入动画是windowAnimation windowAnimation定义在style中.
     */
    protected int[] mAnimations = {R.style.QYQ_Dialog_Animation_Fly,
            R.style.QYQ_Dialog_Animation_Fade,
            R.style.QYQ_Toast_Animation_Fly,
            R.style.QYQ_Toast_Animation_Fade,
            R.style.QYQ_Dialog_Animation_FlyInFadeOut,
            R.style.QYQ_Dialog_Animation_FlyInFlyOut,
            R.style.QYQ_Toast_Animation_FlyInFlyOut,
            R.style.QYQ_Toast_Animation_FlyTopInFlyTopOut,
            R.style.QYQ_Dialog_Animation_RightInRightOut};
    private FrameLayout bt_back;
    private RelativeLayout bt_download_qrcode;
    private Bitmap imageBitmap;
    private HandlerThread loadQrcodeThread;
    private Handler loadQrcodeHandler;
    private Handler showViewHandler;
    private ImageView imageView;
    private String path;

    public ShowQRCodeDialog(Context context, Bitmap bitmap) {
        super(context, R.style.showQRCDialog);
        View rootview = getLayoutInflater().inflate(R.layout.dialog_show_qrcode, null);
        setContentView(rootview);
        mWindow = getWindow();
        mContext = context;
        imageBitmap = bitmap;
        initView();
        imageView = rootview.findViewById(R.id.view_qrcode);
        if (imageBitmap == null) {
            loadQrcode();
        } else {
            showQRCODEView();
        }
        TextView text_tip_info = rootview.findViewById(R.id.text_tip_info);
        text_tip_info.setText(Html.fromHtml("用<font color='#2ac2b9'>圈一圈APP</font>扫此码,加我为好友"));
        bt_back = rootview.findViewById(R.id.bt_back);
        bt_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        bt_download_qrcode = rootview.findViewById(R.id.bt_download_qrcode);
        bt_download_qrcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imageBitmap != null) {
                    saveQRcode();
                }
            }
        });
    }

    public static final Bitmap getImage(String imagePath) throws FileNotFoundException {

        FileInputStream stream = new FileInputStream(imagePath);
        try {
            Bitmap bm = BitmapFactory.decodeFile(imagePath);
            return bm;
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
            }
        }
    }

    private void initView() {
        mWindow.setWindowAnimations(mAnimations[AnimationType.DIALOG_RIGHT_IN_RIGHT_OUT.getValue()]);
        mWindow.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams layoutParams = mWindow.getAttributes();
        WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        layoutParams.width = display.getWidth();
        layoutParams.height = display.getHeight();
        mWindow.setAttributes(layoutParams);
    }

    private void initHandler() {
        if (loadQrcodeThread == null) {
            loadQrcodeThread = new HandlerThread("loadQrCodeBitmap");
            loadQrcodeThread.start();
        }
        if (loadQrcodeHandler == null) {
            loadQrcodeHandler = new Handler(loadQrcodeThread.getLooper());
        }
        if (showViewHandler == null) {
            showViewHandler = new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 10002) {
                        showQRCODEView();
                    } else if (msg.what == 10003) {
                        mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
                        Toast.makeText(mContext, "成功保存二维码图片到相册！", Toast.LENGTH_SHORT).show();
                    } else if (msg.what == 10004) {
                        Toast.makeText(mContext, "保存二维码图片到相册失败！", Toast.LENGTH_SHORT).show();
                    }
                }
            };
        }

    }

    private void loadQrcode() {
        initHandler();
        loadQrcodeHandler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    imageBitmap = getImage(QRCodeManager.codeUser);
                    if (imageBitmap != null && showViewHandler != null) {
                        showViewHandler.sendEmptyMessage(10002);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    if (imageBitmap == null) {
                        LogUtil.e("yjl", "");
                    }
                }
            }
        });
    }

    private Runnable copyQRCodeRunable = new Runnable() {
        @Override
        public void run() {
            try {
                File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

                UserEntity userEntity = UserManager.getUesrInfo(mContext);
                File file = new File(directory, "Camera/" + userEntity.realname + "的圈一圈二维码.jpg");
                if (!file.exists()) {
                    file.createNewFile();
                }
                path = file.getPath();
                if (imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file))) {
                    if (showViewHandler != null) {
                        showViewHandler.sendEmptyMessage(10003);
                    }
                } else {
                    if (showViewHandler != null) {
                        showViewHandler.sendEmptyMessage(10004);
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    private void saveQRcode() {
        initHandler();
        loadQrcodeHandler.post(copyQRCodeRunable);
    }

    private void showQRCODEView() {
        if (imageBitmap != null) {
            imageView.setImageBitmap(imageBitmap);
        }
    }

    /**
     * 释放资源
     */
    public void recycle() {
        if (imageBitmap != null) {
            imageBitmap.recycle();
        }
        if (loadQrcodeThread != null) {
            loadQrcodeThread.quit();
            loadQrcodeThread = null;
        }
        if (loadQrcodeHandler != null) {
            loadQrcodeHandler.removeCallbacksAndMessages(null);
            loadQrcodeHandler = null;
        }
        if (showViewHandler != null) {
            showViewHandler.removeCallbacksAndMessages(null);
            showViewHandler = null;
        }
    }
}
